#基于python语言的火灾监控报警系统客户端
import cv2
import tkinter as tk
from tkinter import messagebox
import socket
import threading
import time
from PIL import Image, ImageTk

# MJPG视频流地址
video_stream_url = "http://192.168.10.1:8080/?action=stream"
# TCP服务器地址和端口
server_ip = "192.168.10.1"
server_port = 1023

# 创建TCP套接字并连接到服务器
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    client_socket.connect((server_ip, server_port))

    
except socket.error as e:
    messagebox.showerror("Connection Error", f"Failed to connect to server: {e}")
    exit(1)

# 发送 'a' 字符连续五次，每次间隔0.1秒
def send_a_sequence():
    global is_button_pressed
    while is_button_pressed:
        for _ in range(5):
            try:
                client_socket.send('a'.encode())
                time.sleep(0.1)
            except socket.error as e:
                messagebox.showerror("Send Error", f"Failed to send 'a' to server: {e}")
                break

# 按钮按下回调
def shout_button_press():
    for _ in range(5):
        try:
            client_socket.send('a'.encode())
            time.sleep(0.1)
        except socket.error as e:
            messagebox.showerror("Send Error", f"Failed to send 'a' to server: {e}")


# 按钮松开回调
def shout_button_release():
    try:
        client_socket.send('b'.encode())
    except socket.error as e:
        messagebox.showerror("Send Error", f"Failed to send 'b' to server: {e}")


# 退出按钮回调
def exit_button_click():
    try:
        client_socket.send('c'.encode())
    except socket.error as e:
        messagebox.showerror("Send Error", f"Failed to send 'c' to server: {e}")
    finally:
        client_socket.close()
        root.destroy()


# 初始化Tkinter
root = tk.Tk()
root.geometry("640x580")
root.title("基于NetStudio的网络监控火灾报警系统")

# 创建一个画布用于显示视频
canvas = tk.Canvas(root, width=640, height=480)
canvas.pack()

# 创建Shout按钮
shout_button = tk.Button(root, text="Shout", command=shout_button_press,width=25, fg="white", bg="blue", font=("Arial", 16))
shout_button.pack(side=tk.LEFT,expand=tk.YES, fill=tk.BOTH)
shout_button.bind("<ButtonRelease-1>", lambda event: shout_button_release())

# 创建一个文本框用于显示服务器消息
message_text = tk.Text(root, height=5, width=30, bd=2, padx=5, pady=5)
message_text.pack(side=tk.LEFT,expand=tk.YES, fill=tk.BOTH)

# 创建Exit按钮
exit_button = tk.Button(root, text="Exit", command=exit_button_click,width=15, height=2, fg="white", bg="red", font=("Arial", 16))
exit_button.pack(side=tk.RIGHT,expand=tk.YES, fill=tk.BOTH)


# 接收服务器消息并显示
def update_message_text(data):
    message_text.insert(tk.END, data + "\n")
    message_text.see(tk.END)

def receive_and_display():
    while True:
        try:
            data = client_socket.recv(1024)
            if data:
                try:
                    decoded_data = data.decode('utf-8')
                except UnicodeDecodeError:
                    decoded_data = data.decode('latin-1')  # 尝试另一种编码
                root.after(0, lambda d=decoded_data: update_message_text(d))
        except socket.error as e:
            break

def clear_textbox():
    message_text.delete(1.0, tk.END)
    # 每隔5秒再次调用自身，实现定时清除
    root.after(5000, clear_textbox)

# 启动接收消息线程
receive_thread = threading.Thread(target=receive_and_display)
receive_thread.start()



# 显示视频流
def show_video():
    cap = cv2.VideoCapture(video_stream_url)
    while True:
        ret, frame = cap.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            pil_image = Image.fromarray(frame)
            photo = ImageTk.PhotoImage(pil_image)
            canvas.create_image(0, 0, image=photo, anchor=tk.NW)
            root.update_idletasks()
            root.update()
        else:
            break
    cap.release()

# 在根窗口初始化完成后启动视频显示
root.after(0, show_video)

# 启动定时清除文本框内容的任务
root.after(5000, clear_textbox)

# 启动Tkinter主循环
root.mainloop()